<gm:page title="Demo - Combine feeds" authenticate="false" onload="init()" onunload="deleteAggregateList()">

  <script>
    var cnnList;
    var msnbcList;
    var foxNewsList;
    var aggregateList;
    
    var cnnListLoaded = false;
    var msnbcListLoaded = false;
    var foxNewsListLoaded = false;

    function init() {
      cnnList = google.mashups.getObjectById('cnnList');
      msnbcList = google.mashups.getObjectById('msnbcList');
      foxNewsList = google.mashups.getObjectById('foxNewsList');
      aggregateList = google.mashups.getObjectById('aggregateList');
    }
    
    function foxNewsListHandler() {
      if (!foxNewsListLoaded) {
        copyList(foxNewsList, 'Fox News');
      }
      foxNewsListLoaded = true;
    }

    function msnbcListHandler() {
      if (!msnbcListLoaded) {
        copyList(msnbcList, 'MSNBC');
      }
      msnbcListLoaded = true;
    }

    function cnnListHandler() {
      if (!cnnListLoaded) {
        copyList(cnnList, 'CNN');
      }
      cnnListLoaded = true;
    }

    function copyList(list, srcString) {
      for (var i=0; i<list.getData().size(); i++) {
        var entry = list.getData().entryAt(i);
        new GPath('gmd:source').setValue(entry, srcString);
        aggregateList.getData().addEntry(entry);
      }
    }
    
    function deleteAggregateList() {
      for (var i=aggregateList.getData().size()-1; i>=0; i--) {
        aggregateList.getData().removeEntry(aggregateList.getData().entryAt(i));
      }
      foxNewsListLoaded = false;
      msnbcListLoaded = false;
      cnnListLoaded = false;
    }
  </script>

  <div class="gm-app-header">
    <h2>Aggregating/combining feeds using JavaScript<h2>
  </div>
  
  <gm:list id="foxNewsList" data="http://feeds.foxnews.com/foxnews/latest" style="display:none">
    <gm:handleEvent event="repaint" execute="foxNewsListHandler()" />
  </gm:list>
    
  <gm:list id="msnbcList" data="http://rss.msnbc.msn.com/id/3032524/device/rss/rss.xml" style="display:none">
    <gm:handleEvent event="repaint" execute="msnbcListHandler()" />
  </gm:list>
  
  <gm:list id="cnnList" data="http://rss.cnn.com/rss/cnn_topstories.rss" style="display:none">
    <gm:handleEvent event="repaint" execute="cnnListHandler()" />
  </gm:list>

  <gm:list id="aggregateList" data="${tmp}/aggregatedFeeds" sort="updatedSort" pagesize="100" template="aggregateListTemplate">
    <gm:sort name="updatedSort" ref="atom:updated"/>
  </gm:list>
  
  <gm:template id="aggregateListTemplate">
    <table class="blue-theme" style="width:100%" align="center">
      <thead>
        <tr>
          <th>Title</th>
          <th>Source</th>
          <th>Last updated</th>
        </tr>
      </thead>
      <tr repeat="true">
        <td><gm:text ref="atom:title"/></td>
        <td><gm:text ref="gmd:source"/></td>
        <td><gm:text ref="atom:updated"/></td>
      </tr>
    </table>
  </gm:template>

</gm:page>